import { createRouter, createWebHashHistory } from "vue-router";
import { ElMessage } from "element-plus";
import utils from "assets/js/utils";
const Login = () => import("../components/Login.vue");
const Home = () => import("components/home/Home.vue");
const Welcome = () => import("components/Welcome.vue");
const Users = () => import("components/user/Users.vue");
const Permissions = () => import("components/rights/Permissions.vue");
const Roles = () => import("components/rights/Roles.vue");
const Cate = () => import("components/goods/Cate.vue");
const Params = () => import("components/goods/Params.vue");
const GoodsList = () => import("components/goods/List.vue");
const AddGoods = () => import("components/goods/AddGoods.vue");
const Order = () => import("components/order/Order.vue");
const Report = () => import("components/report/Report.vue");

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome", //重定向到子路由
    children: [
      {
        path: "/welcome",
        component: Welcome
      },
      {
        path: "/users",
        component: Users
      },
      {
        path: "/permissions",
        component: Permissions
      },
      {
        path: "/roles",
        component: Roles
      },
      {
        path: "/categories",
        component: Cate
      },
      {
        path: "/params",
        component: Params
      },
      {
        path: "/list",
        component: GoodsList
      },
      {
        path: "/goods/addGoods",
        component: AddGoods
      },
      {
        path: "/orders",
        component: Order
      },
      {
        path: "/report",
        component: Report
      }
    ]
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 代表从哪个路径跳转而来
  //next 是一个函数,表示放行
  //  next() 放行, next('/login') 强制跳转
  if (to.path === "/login") return next();
  //跳转页面时,刷新token的刷新时间
  utils.saveRefreshTime();
  //获取token
  const tokenStr = window.sessionStorage.getItem("token");
  //没有token,跳转回登录页
  if (!tokenStr) {
    if (from.path === "/login") {
      ElMessage.error({
        showClose: true,
        message: "登录状态过期,请重新登录"
      });
    }
    return next(`/login?redirect=${to.path}`);
  }
  next();
});

export default router;
